<?php
namespace api\modules\v1\controllers;

use Yii;
use api\controllers\RestController;
use api\modules\v1\models\UploadForm;
use yii\web\UploadedFile;
use api\modules\v1\models\FtpForm;
use yii\filters\auth\QueryParamAuth;

class UploadController extends RestController
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className()
        ];
        return $behaviors;
    }

    public function actionCreate()
    {
        if (!Yii::$app->user->can('createRole')) {
            die('no');
        }
        $model = new UploadForm();
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');
            if (! $model->file instanceof UploadedFile || $model->file->error == UPLOAD_ERR_NO_FILE) {
                $model->addError('message', '上传文件不能为空！');
            }
            if ($model->file && $model->validate()) {
                $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
                if (! $model->hasErrors()) {
                    $ftp = new FtpForm();
                    $filename = $model->file->baseName . '.' . $model->file->extension;
                    $remote_file = 'shop/avatar/' . $filename;
                    $local_file = 'uploads/' . $filename;
                    $ftp->put($remote_file, $local_file);
                    if ($ftp->hasErrors()) {
                        return $ftp;
                    } else {
                        @unlink($local_file);
                        return [
                            'name' => $filename,
                            'url'=>'http://shop.mangxiaoquan.com/data/upload/' . $remote_file,
                            'size' => $model->file->size,
                        ];
                    }
                    // sleep(2);
                    // $path = $remote_file;
                    // $ftp->delete($path);
                } else {
                    $model->addError('message', '文件上传失败！');
                }
            }
        }
        return $model;
    }
}